package com.group.service.impl;

import com.group.mapper.CartMapper;
import com.group.mapper.GoodsMapper;
import com.group.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.entity.Cart;
import pojo.qo.UserCart;

import java.util.List;

@Service("cartService")
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;


    @Override
    public int addCart(Cart cart) {
        //判断此商品是否已存在购物车中
        UserCart result = cartMapper.hasCart(cart);
        if (null == result) {
            //不存在，新增此商品进购物车
            int i = cartMapper.insertCart(cart);
            if (i != 1) {
                return 0;
            }
            return i;
        }
        //存在，则只增加此商品的数量
        //拿取新增商品数量
        //加到原有数量中
        result.getGoodList().forEach(good -> {
            cart.setNum(good.getGoodCount()+cart.getNum());
            cart.setCartId(result.getCartId());
        });
        //修改原有数量

        return cartMapper.updateCartCount(cart);
    }

    @Override
    public int updateCart(Cart cart) {
        return cartMapper.updateCartById(cart);
    }

    @Override
    public int deleteCart(Cart cart) {
        return cartMapper.deleteCart(cart);
    }

    @Override
    public List<UserCart> showCart(Long userID) {
        return cartMapper.selectCartByUserId(userID);
    }
}
